package com.tchhy.mvplibrary.ui.adapter

import android.view.LayoutInflater
import android.view.View
import androidx.annotation.LayoutRes
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import com.zhy.view.flowlayout.TagFlowLayout

/**
 * 简单封装TagAdapter
 *
 * Author: wfy
 *
 * time: 2018/9/10
 *
 */
abstract class BaseTagAdapter<T>(@LayoutRes val layoutId: Int, val mDateSet: MutableList<T>? = mutableListOf()) : TagAdapter<T>(mDateSet) {

    private var mTagFlowLayout: TagFlowLayout? = null

    /**
     * 此方法在TagFlowLayout 的setAdapter时调用
     */
    override fun getView(parent: FlowLayout, position: Int, t: T): View {
        val rootView: View = LayoutInflater.from(parent.context).inflate(layoutId, null, false)
        onBindData(rootView, position, t)
        return rootView
    }

    abstract fun onBindData(itemView: View, position: Int, t: T)

    /*
        必须依附TagFlowLayout，不然无法更新数据
     */
    fun replaceData(dataSet: MutableList<T>, tagFlowLayout: TagFlowLayout? = null) {
        if (tagFlowLayout != null) {
            attachTagFlowLayout(tagFlowLayout)
        }
        mDateSet?.apply {
            clear()
            addAll(dataSet)
        }
        this.mTagFlowLayout?.adapter = this
    }

    fun attachTagFlowLayout(tagFlowLayout: TagFlowLayout) {
        if (tagFlowLayout != mTagFlowLayout) {
            this.mTagFlowLayout = tagFlowLayout
        }
    }
}